<!-- 工具管理-工具台账页面 -->
<template>
  <div>
    <div v-show="isMain" id="tool-ledger" v-loading="loading" class="equip-wrap-common" element-loading-background="rgba(255, 255, 255, 1)">
      <!--空状态-->
      <div v-if="isEmpty && loading === false" class="tool-table-empty">
        <px-empty :image="toolsPng" />
        <div class="tool-table-bg">
          <p>还没有被管理的工具</p>
          <h3>一站式管理您业务中所需工具</h3>
          <p>在此页面可以管理所需的工具，可以新增、查看详情、报废，也可以快速批量导入、批量下载</p>
          <div class="tool-table-btns">
            <px-button type="primary" icon="plus" @click="addTools">新增工具</px-button>
            <px-button type="primary" style="margin: 0 8px" plain @click="modelDownload">下载模板</px-button>
            <px-upload action="#" :http-request="handleImport" :show-file-list="false" accept=".xlsx, xls">
              <px-button type="primary" plain>批量导入</px-button>
            </px-upload>
          </div>
        </div>
      </div>
      <div v-else>
        <px-form class="custom-form-ui equip-form" :model="queryParams" inline label-position="right" label-width="120px">
          <px-row :gutter="16">
            <px-col :span="6">
              <px-form-item label="工具名称/编码">
                <px-input
                  v-model="queryParams.toolNameOrCode"
                  placeholder="请输入工具名称/编码"
                  maxlength="50"
                  clearable
                  @blur="queryParams.toolNameOrCode = $event.target.value.trim()"
                  @keyup.enter="queryTable"
                >
                  <template #suffix>
                    <px-icon style="cursor: pointer" @click="queryTable">
                      <search />
                    </px-icon>
                  </template>
                </px-input>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="工具分类">
                <px-select v-model="queryParams.toolCategory" placeholder="请选择工具分类">
                  <px-option v-for="item in toolCategoryList" :key="item.id" :label="item.name" :value="item.value" />
                </px-select>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <!-- <EquipClassSelect customLabel="工具科室" :className="queryParams.className" @changeClassName="changeClassName" /> -->
              <px-form-item label="工具科室">
                <px-select v-model="queryParams.toolClassName" placeholder="请选择工具科室">
                  <px-option v-for="item in classNameList" :key="item.id" :label="item.name" :value="item.value" />
                </px-select>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="资产标签">
                <px-select v-model="queryParams.assetTag" placeholder="请选择资产标签">
                  <px-option v-for="item in assetTagListAll" :key="item.value" :label="item.label" :value="item.value" />
                </px-select>
              </px-form-item>
            </px-col>
            <px-col :span="6">
              <px-form-item label="厂区">
                <px-select v-model="queryParams.factoryAreaCode" placeholder="请选择厂区">
                  <px-option v-for="item in facList" :key="item.id" :label="item.name" :value="item.value" />
                </px-select>
              </px-form-item>
            </px-col>
            <px-col :span="4">
              <px-button type="primary" @click="queryTable">查询</px-button>
              <px-button @click="resetTable">重置</px-button>
            </px-col>
          </px-row>
        </px-form>
        <px-radio-group v-model="toolStatus" style="margin: -5px 0 20px" @change="queryTable()">
          <px-radio-button label="">全部</px-radio-button>
          <px-radio-button v-for="item in toolStatusList" :key="item.value" :label="item.value">{{ item.label }}</px-radio-button>
        </px-radio-group>
        <div class="flex-button-row">
          <px-button v-has="'ALL_EQUIP_TOOLMANAGE_LEDGER_ADD'" type="primary" icon="plus" @click="addTools">新增工具</px-button>
          <px-button v-has="'ALL_EQUIP_TOOLMANAGE_LEDGER_DOWNLOAD_TEMPLATE'" type="primary" plain @click="modelDownload">下载模板</px-button>
          <px-upload
            v-has="'ALL_EQUIP_TOOLMANAGE_LEDGER_BATCH_UPLOAD'"
            action="#"
            :http-request="handleImport"
            :show-file-list="false"
            accept=".xlsx, xls"
          >
            <px-button type="primary" plain>批量导入</px-button>
          </px-upload>
          <px-button
            v-has="'ALL_EQUIP_TOOLMANAGE_LEDGER_BATCH_DOWNLOAD'"
            type="primary"
            plain
            :disabled="selectIds.length == 0"
            @click="batchDownload"
          >
            批量下载
          </px-button>
          <px-button v-has="'ALL_EQUIP_TOOLMANAGE_LEDGER_BATCH_DELETE'" type="primary" plain :disabled="selectIds.length == 0" @click="batchDelete">
            批量删除
          </px-button>
        </div>
        <px-table :data="tableData" class="equip-table" height="calc(100vh - 390px)" border @selection-change="selectionChange">
          <px-table-column type="selection" width="40" />
          <px-table-column label="序号" width="80" fixed="left" align="center">
            <template #default="{ $index }">
              {{ (queryParams.pageNum - 1) * queryParams.pageSize + $index + 1 }}
            </template>
          </px-table-column>
          <px-table-column prop="toolCode" label="工具编码" min-width="200" show-overflow-tooltip>
            <template #default="scope">
              <span v-if="isHasPermission('ALL_EQUIP_TOOLMANAGE_LEDGER_VIEW')" style="color: #3b82f6; cursor: pointer" @click="handleView(scope.row)">
                {{ scope.row.toolCode }}
              </span>
              <span v-else>{{ scope.row.toolCode }}</span>
            </template>
          </px-table-column>
          <px-table-column prop="toolName" label="工具名称" min-width="100" show-overflow-tooltip />
          <px-table-column prop="factoryAreaDesc" label="厂区" min-width="100" show-overflow-tooltip />
          <px-table-column prop="toolStatusDesc" label="工具状态" min-width="120" show-overflow-tooltip>
            <template #default="scope">
              <px-tag
                effect="plain"
                :style="{
                  color: `${tagColorList[scope.row.toolStatus]}`,
                  border: `1px solid ${tagBorderColorList[scope.row.toolStatus]}`,
                  backgroundColor: `${tagBgColorList[scope.row.toolStatus]}`
                }"
              >
                {{ scope.row.toolStatusDesc }}
              </px-tag>
            </template>
          </px-table-column>
          <px-table-column prop="toolCategoryDesc" label="工具分类" min-width="100" show-overflow-tooltip />
          <px-table-column prop="toolUnitDesc" label="工具单位" min-width="100" show-overflow-tooltip />
          <px-table-column prop="toolModel" label="型号/规格" min-width="120" show-overflow-tooltip />
          <px-table-column prop="brandVal" label="品牌" min-width="120" show-overflow-tooltip />
          <px-table-column prop="classNameDesc" label="工具科室" min-width="120" show-overflow-tooltip />
          <px-table-column prop="assetTagDesc" label="资产标签" min-width="120" show-overflow-tooltip />
          <px-table-column prop="custodianName" label="管理人" min-width="120" show-overflow-tooltip />
          <px-table-column prop="updateTime" label="更新时间" min-width="120" show-overflow-tooltip />
          <!-- <px-table-column prop="inDate" label="入库时间" min-width="120" show-overflow-tooltip />
        <px-table-column prop="remark" label="备注" min-width="120" show-overflow-tooltip /> -->
          <px-table-column fixed="right" label="操作" min-width="200" align="center">
            <template #default="scope">
              <px-tooltip content="编辑" placement="top" append-to=".equip-wrap-common">
                <px-button v-has="'ALL_EQUIP_TOOLMANAGE_LEDGER_EDIT'" link type="primary" icon="EditPen" @click="handleEdit(scope.row)" />
              </px-tooltip>
              <px-tooltip append-to=".equip-wrap-common" content="借出" placement="top">
                <px-button
                  v-has="'ALL_EQUIP_TOOLMANAGE_LEDGER_BORROW'"
                  :disabled="scope.row.toolStatus !== 0"
                  link
                  type="primary"
                  @click="handleBorrow(scope.row)"
                >
                  <component :is="markRaw(boxIn)" />
                </px-button>
              </px-tooltip>
              <px-tooltip append-to=".equip-wrap-common" content="归还" placement="top">
                <px-button
                  v-has="'ALL_EQUIP_TOOLMANAGE_LEDGER_REVERT'"
                  :disabled="scope.row.toolStatus !== 1"
                  link
                  type="primary"
                  @click="handleRevert(scope.row)"
                >
                  <component :is="markRaw(boxOut)" />
                </px-button>
              </px-tooltip>
              <px-tooltip append-to=".equip-wrap-common" content="详情" placement="top">
                <px-button v-has="'ALL_EQUIP_TOOLMANAGE_LEDGER_VIEW'" link type="primary" icon="Tickets" @click="handleView(scope.row)" />
              </px-tooltip>
              <px-tooltip v-if="scope.row.toolStatus === 0" append-to=".equip-wrap-common" content="报废" placement="top">
                <px-button v-has="'ALL_EQUIP_TOOLMANAGE_LEDGER_SCAPE'" link type="danger" icon="CloseRectangle" @click="handleScrap(scope.row)" />
              </px-tooltip>
            </template>
          </px-table-column>
        </px-table>
        <pagination
          v-show="total > 0"
          v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize"
          class="equip-table-pagination"
          :total="total"
          @pagination="queryTable"
        />
      </div>
    </div>
    <!-- 详情新增/编辑页面 -->
    <AddToolDetail :isMain="isMain" :isView="isView" :toolId="toolId" @queryTable="queryTable" @backMainPage="backMainPage" />
    <!-- 详情查看页面 -->
    <ViewToolDetail :isMain="isMain" :isView="isView" :toolId="toolId" @backMainPage="backMainPage" />
    <!-- 报废弹窗 -->
    <AddToolDialog :visible="dialogVisible" :toolId="toolId" @closeDialog="closeDialog" @queryTable="queryTable" />
    <!-- 归还弹窗 -->
    <RevertToolDialog
      :visible="revertVisible"
      :isSimple="true"
      :isShowDetail="true"
      :toolId="toolId"
      :rowData="rowData"
      @closeDialog="closeRevertDialog"
      @queryTable="queryTable"
    />
    <ErrorDialog :visible="isErrorShow" :errData="errData" @closeDialog="closeErrDialog" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "ALL_EQUIP_TOOLMANAGE_LEDGER"
});
import { queryDictData } from "@/api/common";
import { deleteBatchTool, getToolImport, queryAllToolLedger } from "@/api/equip/toolManage";
import toolsPng from "@/assets/images/tools/empty.png";
import boxIn from "@/assets/svg/operation/box_in.svg?component";
import boxOut from "@/assets/svg/operation/box_out.svg?component";
import { isHasPermission } from "@/utils/auth";
import { PxMessage, PxMessageBox } from "px-ui";
import { getCurrentInstance, markRaw, onMounted, reactive, toRefs } from "vue";
import { useRoute, useRouter } from "vue-router";
import { assetTagList, toolStatusList } from "../data";
import RevertToolDialog from "../loanReturn/components/RevertToolDialog.vue";
import AddToolDetail from "./components/AddToolDetail.vue";
import AddToolDialog from "./components/AddToolDialog.vue";
import ErrorDialog from "./components/ErrorDialog.vue";
import ViewToolDetail from "./components/ViewToolDetail.vue";

const { proxy }: any = getCurrentInstance();

const assetTagListAll = [{ label: "全部", value: "" }, ...assetTagList];

const state = reactive<any>({
  isMain: true, // 主页面true 详情页面false
  isView: true, // 查看true 新增/编辑false
  toolStatus: "",
  queryParams: {
    toolNameOrCode: "",
    toolClassName: "",
    toolCategory: "",
    assetTag: "",
    pageNum: 1,
    pageSize: 20
  },
  toolCategoryList: [],
  tableData: [],
  total: 0,
  selectIds: [],
  toolId: undefined,
  rowData: undefined,
  dialogVisible: false,
  revertVisible: false,
  loading: true,
  isEmpty: false,
  isErrorShow: false,
  errData: {},
  classNameList: [],
  facList: []
});
const {
  isMain,
  isView,
  toolCategoryList,
  tableData,
  toolStatus,
  queryParams,
  total,
  selectIds,
  toolId,
  rowData,
  dialogVisible,
  revertVisible,
  loading,
  isEmpty,
  isErrorShow,
  errData,
  classNameList,
  facList
} = toRefs(state);

const tagColorList = {
  0: "#10B981",
  1: "#EF4444",
  3: "#909399"
};

const tagBorderColorList = {
  0: "#B7EAD9", // 在库
  1: "#FAC7C7", // 出库
  3: "#7997A8" // 报废
};

const tagBgColorList = {
  0: "#E8F8F3",
  1: "#FEECEC",
  3: "#F7F7F7"
};

// const isEmpty = computed(() => {
//   const { toolNameOrCode, className, toolCategory, assetTag } = queryParams.value;
//   return tableData.value?.length === 0 && toolStatus.value === "" && !toolNameOrCode && !className && !toolCategory && !assetTag;
// });

const route = useRoute();
// 进入页面时触发
onMounted(() => {
  const { id, type } = route.query;
  if (type === "view") {
    toolId.value = id;
    isMain.value = false;
    isView.value = true;
  }
  queryClassNameSelect();
  queryTable();
});

// // 科室组件调用父组件
// const changeClassName = val => {
//   queryParams.value.className = val;
// };

// 工具科室下拉框
const queryClassNameSelect = async () => {
  const toolCategoryData = await queryDictData({ typeCode: "toolCategory" });
  classNameList.value = await queryDictData({ typeCode: "className" });
  facList.value = await queryDictData({ typeCode: "factoryArea" });
  toolCategoryList.value = [{ name: "全部", value: "", id: -1 }, ...toolCategoryData];
};
// 查询工具列表
const queryTable = async () => {
  loading.value = true;
  const { toolNameOrCode, toolClassName, toolCategory, assetTag, factoryAreaCode } = queryParams.value;
  const data = await queryAllToolLedger({ ...queryParams.value, toolStatus: toolStatus.value });
  tableData.value = data?.data || [];
  total.value = data?.total || 0;
  loading.value = false;
  if (
    tableData.value?.length === 0 &&
    toolStatus.value === "" &&
    !toolNameOrCode &&
    !toolClassName &&
    !toolCategory &&
    !assetTag &&
    !factoryAreaCode
  ) {
    isEmpty.value = true;
  } else {
    isEmpty.value = false;
  }
  // downloadParams.value = {
  //   ids: [],
  //   spareNameOrCode: queryParams.value.spareNameOrCode,
  //   className: queryParams.value.className,
  //   systemVal: queryParams.value.systemVal
  // };
};
// 重置筛选条件和工具列表
const resetTable = async () => {
  toolStatus.value = "";
  queryParams.value = {
    toolNameOrCode: "",
    toolClassName: "",
    toolCategory: "",
    assetTag: "",
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize
  };
  queryTable();
};

import { dataList } from "@/api/system/dictData";
// 下载模版
const modelDownload = async () => {
  const info = await dataList({ typeCode: "TOOL_IMPORT_TEMPLATE" });
  proxy.download("post", "/sharing/api/v1/file/download", { id: info[0]?.itemDesc }, "工具台账信息模板.xlsx");
};

const closeErrDialog = () => {
  errData.value = {};
  isErrorShow.value = false;
};

const handleImport = async (options: any) => {
  try {
    console.log("导入文件", options);
    const { file } = options;
    const formData = new FormData();
    formData.append("file", file);
    const res = await getToolImport(formData);
    if (res?.result) {
      PxMessage.success("批量导入成功");
      queryTable();
    } else {
      isErrorShow.value = true;
      errData.value = res;
    }
  } catch (error) {
    console.log(error);
  }
};
// 表格多选框选中
const selectionChange = (val: any) => {
  selectIds.value = [];
  val.forEach((item: any) => {
    if (item.id) {
      selectIds.value.push(item.id);
    }
  });
};
// 批量下载
const batchDownload = async () => {
  // downloadParams.value.ids = selectIds.value;
  // const params = downloadParams.value;
  proxy.download("post", "/digitaltwins/api/v1/toolInfo/exportToolInfo", { ids: selectIds.value }, "工具台账.xlsx");
};
// 批量删除
const batchDelete = async () => {
  PxMessageBox.confirm(`要删除当前工具吗？`, "提示", {
    confirmButtonText: "删除",
    confirmButtonClass: "px-button--danger",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      await deleteBatchTool({ ids: selectIds.value });
      PxMessage.success("删除成功");
      queryTable();
    })
    .catch(() => {});
};

const handleEdit = row => {
  isMain.value = false;
  isView.value = false;
  toolId.value = row.id;
};
// 查看工具详情
const handleView = (row: any) => {
  const { toolStatus, id } = row;
  toolId.value = id;
  isMain.value = false;
  isView.value = true;
};
// 工具报废
const handleScrap = (row: any) => {
  toolId.value = row.id;
  dialogVisible.value = true;
};
// 工具报废-关闭弹窗
const closeDialog = () => {
  toolId.value = "";
  dialogVisible.value = false;
};
// 工具归还
const handleRevert = (row: any) => {
  rowData.value = row;
  revertVisible.value = true;
};
// 工具归还-关闭弹窗
const closeRevertDialog = () => {
  rowData.value = undefined;
  revertVisible.value = false;
};

// 厂区组件调用父组件
const changeFactory = val => {
  queryParams.value.factoryAreaCode = val;
};

const router = useRouter();

const handleBorrow = row => {
  router.push(`/all/equip/toolManage/loanReturn?id=${row.id}&type=add`);
};
// 添加工具详情
const addTools = () => {
  isMain.value = false;
  isView.value = false;
};
// 从新增/编辑、详情返回主页面
const backMainPage = () => {
  isMain.value = true;
  toolId.value = "";
  if (route?.query && route?.query?.id) {
    router.push({ query: {} });
  }
};
</script>

<style lang="scss" scoped>
@import url("@/views/all/equip/scss/table-list.scss");

.tool-table-empty {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: space-around;
  width: 400px;
  // height: 140px;
  margin: 0 auto;

  .tool-table-bg {
    margin-top: -60px;
    background-color: #fff;

    h3 {
      font-size: 18px;
      font-weight: 600;
    }

    p {
      margin: 8px 0;
      font-size: 14px;
      line-height: 1.75;
      text-align: left;
    }

    p:first-child {
      color: rgb(0 0 0 / 60%);
    }

    p:nth-child(2) {
      color: rgb(0 0 0 / 80%);
    }
  }

  .tool-table-btns {
    display: flex;
  }
}
</style>
